package me.zhengjie.utils;

import java.util.concurrent.*;

public class ExecutorUtil {

    private static volatile ExecutorUtil executorUtil;

    private static final int corePoolSize = 5;

    private static final int maxPoolSize = 10;

    private static final long keepAliveTime = 1L;

    private static final TimeUnit minutes = TimeUnit.MINUTES;

    private static final BlockingQueue<Runnable> blockingDeque = new LinkedBlockingDeque<>(1000);

    private static final ThreadFactory factory = Executors.defaultThreadFactory();

    private static final RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

    private ThreadPoolExecutor executor = null;

    private final int queueCapacity = 1000;

    public ExecutorService getExecutorServer() {
        // 如果executor为空，则创建一个新的ThreadPoolExecutor
        if (executor == null) {
            return executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                    minutes, blockingDeque, factory, handler);
        }
        return executor;
    }

    public ExecutorService getExecutorServer(int corePoolSize, int maxPoolSize, long keepAliveTime,
                                             TimeUnit minutes, BlockingQueue<Runnable> blockingDeque,
                                             ThreadFactory factory, RejectedExecutionHandler handler) {
        // 如果executor为空，则创建一个新的ThreadPoolExecutor
        if (executor == null) {
            return executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                    minutes, blockingDeque, factory, handler);
        }
        return executor;
    }

    public static  ExecutorUtil getExecutorUtil() {
        if (executorUtil == null) {
            // 加锁
            synchronized (ExecutorUtil.class) {
                // 第二次检查
                if (executorUtil == null) {
                    // 创建实例
                    executorUtil = new ExecutorUtil();
                }
            }
        }
        return executorUtil;
    }

}
